import React, {useEffect, useState} from 'react';
import {Avatar, Card, CardContent, CardHeader, Divider, Grid, TextField, Tooltip, Typography} from "@material-ui/core";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import {faExclamation} from "@fortawesome/free-solid-svg-icons";
import {countWords} from "../../../../../../../assets/functions/functions";
import {useDispatch, useSelector} from "react-redux";
import {validateIndicatorName} from "../../../../../../../redux/reducers/editor";
import EditIcon from '@material-ui/icons/Edit';
import SnackbarMessage from "../../../../Common/Snackbar/SnackbarMessage";
import Button from "@material-ui/core/Button";
import DoneIcon from "@material-ui/icons/Done";

export default function Preview(props) {
  // Props
  const {
    classes,
    indicatorName,
    indicatorNameAvailable,
    indicatorType,
    displayCodeData,
    scriptCodeData,
    indicatorPreviewData
  } = props;

  const confirmed = useSelector(state => state.editor.selectedData.indicatorName.confirmed);

  // Local constants
  const dispatch = useDispatch();
  const [errorInput, setErrorInput] = useState(false);
  const [selection, setSelection] = useState({
    indicatorName: indicatorName ? indicatorName : "",
    errorMessage: "",
  });

  useEffect(() => {
    const script = document.createElement("script");
    script.innerHTML = scriptCodeData;
    document.getElementById("root").appendChild(script);
    return () => {
      document.getElementById("root").removeChild(script);
    };
  }, [scriptCodeData]);

  const handleSetIndicatorName = (e) => {
    const {name, value} = e.target;
    setSelection({
      ...selection,
      [name]: value
    });
    if (errorInput)
      setErrorInput(false)
  };

  const handleIndicatorNameCreated = (e) => {
    e.preventDefault();
    if (selection.indicatorName) {
      if (countWords(selection.indicatorName) > 2) {
        dispatch(validateIndicatorName(selection.indicatorName));
      } else {
        setSelection({
          ...selection,
          errorMessage: "Name is too short, try again with at least four words to describe the indicator."
        });
        setErrorInput(!errorInput);
      }
    } else {
      setSelection({
        ...selection,
        errorMessage: "A name for the indicator is required!"
      });
      setErrorInput(!errorInput);
    }
  }

  return (
    <>
      <Card elevation={10}>
        <CardHeader
          avatar={
            !indicatorNameAvailable ? (
              <Tooltip arrow placement="bottom"
                       title={<Typography>Indicator name not available!</Typography>}>
                <Avatar className={classes.avatarError}><Typography variant={"h5"}>
                  <FontAwesomeIcon icon={faExclamation} size="sm"/>
                </Typography></Avatar>
              </Tooltip>
            ) : <></>
          }
          title={<>
            {!confirmed ? (
              <form onSubmit={handleIndicatorNameCreated}>
                <Grid container alignItems="center">
                  <Grid item xs style={{paddingRight: "16px"}}>
                    <TextField
                      autoFocus
                      id="indicatorName"
                      name="indicatorName"
                      required
                      margin="dense"
                      value={selection.indicatorName}
                      onChange={(e) => handleSetIndicatorName(e)}
                      placeholder="Name the indicator e.g. Students weekly learning resource access"
                      fullWidth
                      error={errorInput}
                      helperText={errorInput ? selection.errorMessage : ""}
                    />
                  </Grid>
                  <Grid item>
                    <Tooltip arrow placement="top"
                             title="Confirm indicator name" >
                      <Button variant="outlined" color="primary" endIcon={<DoneIcon/>} type="submit">
                        Confirm
                      </Button>
                    </Tooltip>
                  </Grid>
                </Grid>
              </form>
            ) : (
              <Grid container alignItems="center">
                <Grid item xs>
                  <Grid container direction="column">
                    <Typography variant="h6">{selection.indicatorName}</Typography>
                    <Typography variant="overline">{indicatorType}</Typography>
                  </Grid>
                </Grid>
                <Grid item>
                  <Grid container>
                    <Grid item className={classes.gutterLeftRightLarge}>
                      <Tooltip arrow placement="bottom"
                               title="Edit indicator name" >
                        <Button variant="outlined" startIcon={<EditIcon/>}
                                onClick={handleIndicatorNameCreated}>
                          Edit
                        </Button>
                      </Tooltip>
                    </Grid>
                  </Grid>

                </Grid>
              </Grid>
            )}
          </>}/>
        <Divider/>
        <CardContent style={{backgroundColor: '#fff'}}>
          <Grid container justify="center" alignItems="center"
                className={classes.gutterTopBottomLarge} style={{color: "#000"}}>
            {displayCodeData}
          </Grid>
        </CardContent>
      </Card>

      <SnackbarMessage
        message={"An indicator with same name already exists, please rephrase the name of the indicator"}
        type={"error"}
        openSnackbar={confirmed && !indicatorNameAvailable}
        setOpenSnackbar={setErrorInput}
        duration={3000}
      />

    </>
  );
}
